package fun.cyhgraph.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import fun.cyhgraph.annotation.AuthCheck;
import fun.cyhgraph.common.ErrorCode;
import fun.cyhgraph.common.UserConstant;
import fun.cyhgraph.common.UserRoleEnum;

import fun.cyhgraph.mapper.UserMapper;
import fun.cyhgraph.model.dto.*;
import fun.cyhgraph.model.entity.Employee;
import fun.cyhgraph.model.entity.MerchantInfo;
import fun.cyhgraph.model.entity.User;
import fun.cyhgraph.exception.BusinessException;
import fun.cyhgraph.exception.ThrowUtils;
import fun.cyhgraph.result.PageResult;
import fun.cyhgraph.result.Result;
import fun.cyhgraph.service.EmployeeService;
import fun.cyhgraph.service.MerchantInfoService;
import fun.cyhgraph.service.UserService;
import fun.cyhgraph.model.vo.EmployeeLoginVO;
import fun.cyhgraph.model.vo.UserLoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/admin/user")
@Tag(name = "系统用户管理")
@Slf4j
public class AdminController {
    /**
     * 盐值，混淆密码
     */
    public static final String SALT = "rush";
    @Resource
    private EmployeeService employeeService;
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private MerchantInfoService merchantInfoService;

    /**
     * 用户注册(管理员注册)
     * @return
     */
    @Operation(summary = "用户注册(管理员)")
    @PostMapping("/adminRegister")
    public Result<EmployeeLoginVO> adminRegister(@RequestBody UserRegisterForAdminDTO userRegisterDTO , HttpServletRequest request){
        List<Integer> gender = Arrays.asList(0, 1);
        if (userRegisterDTO == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "参数错误");
        }
//        User loginUser = userService.getLoginUser(request, "权限不足，仅能管理员权限注册(请先登录管理员账号)");
//        if (!loginUser.getRole().equals(UserRoleEnum.ADMIN.getValue())){
//            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR , "权限不足，请重新登录");
//        }
//        校验参数
        userService.verifyAdmin(userRegisterDTO);
        // 3. 插入数据
        User user = new User();
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userRegisterDTO.getPassword()).getBytes());
        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setPassword(encryptPassword);
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setRole(UserRoleEnum.ADMIN.getValue());
        //插入
        int insert = userMapper.insert(user);
        if (insert == 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return Result.success("管理员注册成功");
    }
    /**
     * 用户注册(商家注册)
     * @return
     */
    @Operation(summary = "用户注册(商家注册)")
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/merchantRegister")
    public Result<EmployeeLoginVO> merchantRegister(@RequestBody RegisterForMerchantDTO userRegisterDTO , HttpServletRequest request){
        List<Integer> gender = Arrays.asList(0, 1);
        if (userRegisterDTO == null || !gender.contains(userRegisterDTO.getGender())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "参数错误");
        }
//        校验参数
        userService.verifyMerchant(userRegisterDTO);
        User user1 = userService.getLoginUser(request , "权限不足，仅能管理员权限注册 ");
        if (!user1.getRole().equals(UserRoleEnum.ADMIN.getValue())){
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR , "权限不足，请重新登录");
        }
        // 3. 赋值
        User user = new User();
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userRegisterDTO.getPassword()).getBytes());
        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setPassword(encryptPassword);
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setRole(UserRoleEnum.MERCHANT.getValue());
        //插入到用户表
        int insert = userMapper.insert(user);
        if (insert == 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        //插入到商家信息表
        MerchantInfo merchantInfo = new MerchantInfo();
        BeanUtils.copyProperties(userRegisterDTO, merchantInfo);
        merchantInfo.setMerchantId(user.getId());
        merchantInfo.setCreateTime(LocalDateTime.now());
        merchantInfo.setUpdateTime(LocalDateTime.now());
        merchantInfo.setMerchantStatus(0);
        merchantInfo.setCreateUser(user1.getId());

        //校验merchantInfo表中是否存在merchantId为userId的数据
        MerchantInfo merchantInfo1 = merchantInfoService.getOne(new QueryWrapper<MerchantInfo>().eq("merchant_id", user.getId()));
        if (merchantInfo1 != null){
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR , "商家信息已存在，请勿重复注册！");
        }
        //插入
        boolean save = merchantInfoService.save(merchantInfo);
        if (!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }

        return Result.success("管理员注册成功");
    }
    @Operation(summary = "用户注册(骑手注册)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/riderRegister")
    public Result<EmployeeLoginVO> loginForAdmin(@RequestBody UserRegisterForAdminDTO userRegisterDTO){
        List<Integer> gender = Arrays.asList(0, 1);
        if (userRegisterDTO == null || !gender.contains(userRegisterDTO.getGender())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "参数错误");
        }
//        校验参数
        userService.verifyRider(userRegisterDTO);
        // 3. 插入数据
        User user = new User();
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userRegisterDTO.getPassword()).getBytes());
        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setPassword(encryptPassword);
        user.setStatus(0);
        user.setCreateTime(LocalDateTime.now());
        user.setRole(UserRoleEnum.RIDER.getValue());
        //插入
        int insert = userMapper.insert(user);
        if (insert == 0) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        }
        return Result.success("尊敬的骑手"+",您注册成功");
    }

    /**
     * 用户登录
     */
    @Operation(summary = "管理端用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request ) {
        if (userLoginDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String name = userLoginDTO.getName();
        String password = userLoginDTO.getPassword();

        if (StringUtils.isAnyBlank(name, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserLoginVO loginUserVO = userService.userLogin(name, password, request);
        return Result.success(loginUserVO);
    }
    /**
     * 删除用户
     *
     * @param request
     * @return
     */

    @Operation(summary = "删除用户")
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> deleteUser(@RequestBody DeleteUserDto deleteUserDto, HttpServletRequest request) {
        if (deleteUserDto == null || deleteUserDto.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteUserDto.getId());
        if (!b){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"删除失败");
        }
//        //移除登录态
//        userService.userLogout(request);
        return Result.success(b);
    }

    /**
     * 更新用户
     * @param request
     * @return
     */
    @Operation(summary = "更新用户")
    @PostMapping("/update")
    public Result<Boolean> updateUser(@RequestBody UserUpdateDto userUpdateDto,
                                      HttpServletRequest request) {
        if (userUpdateDto == null || userUpdateDto.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        //查询当前用户的信息
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        if (!loginUser.getId().equals(userUpdateDto.getId()) && !UserRoleEnum.ADMIN.equals(loginUser.getRole())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        BeanUtils.copyProperties(userUpdateDto, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success("更新成功");
    }
    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @Operation(summary = "根据 id 获取用户")
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public Result<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return Result.success(user);
    }
//    /**
//     * 分页获取用户列表（仅管理员）
//     *
//     * @param userQueryRequest
//     * @param request
//     * @return
//     */
//    @Operation(summary = "分页获取用户列表")
//    @PostMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public Result<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest,
//                                             HttpServletRequest request) {
//        long current = userQueryRequest.getCurrent();
//        long size = userQueryRequest.getPageSize();
//        Page<User> userPage = userService.page(new Page<>(current, size),
//                userService.getQueryWrapper(userQueryRequest));
//        return Result.success(userPage);
//    }
    /**
     * 根据id启用禁用员工
     * @param id
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Operation(summary = "根据id启用禁用员工")
    @PutMapping("/status/{id}")
    public Result onOff(@PathVariable Integer id){
        employeeService.onOff(id);
        return Result.success("ok");
    }
    /**
     * 员工条件分页查询
     * @param pageDTO
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Operation(summary = "员工条件分页查询")
    @GetMapping("/page")
    public Result<PageResult> employeePageList(PageDTO pageDTO){
        log.info("前端传过来的page参数：{}", pageDTO);
        PageResult pageResult = employeeService.employeePageList(pageDTO);
        return Result.success(pageResult);
    }



















































//    /**
//     * 员工注册（其实就是新增操作而已，和token什么的无关！）
//     * @return
//     */
//    @PostMapping("/register")
//    public Result register(@RequestBody EmployeeLoginDTO employeeLoginDTO){
//        log.info("用户传过来的注册信息(和登录格式一样的DTO):{}", employeeLoginDTO);
//        employeeService.register(employeeLoginDTO);
//        return Result.success();
//    }

//    /**
//     * 修改当前登录账号的密码
//     * @param employeeFixPwdDTO
//     * @return
//     */
//    @PutMapping("/fixpwd")
//    public Result fixPwd(@RequestBody EmployeeFixPwdDTO employeeFixPwdDTO){
//        log.info("新旧密码信息：{}", employeeFixPwdDTO);
//        employeeService.fixPwd(employeeFixPwdDTO);
//        return Result.success();
//    }
//
//    /**
//     * 新增员工
//     * @param employeeDTO
//     * @return
//     */
//    @PostMapping("/add")
//    public Result addEmployee(@RequestBody EmployeeDTO employeeDTO){
//        log.info("新增用户的信息：{}", employeeDTO);
//        employeeService.addEmployee(employeeDTO);
//        return Result.success();
//    }
//
//    /**
//     * 根据id获取员工信息
//     * @return
//     */
//    @GetMapping("/{id}")
//    public Result<Employee> getEmployeeById(@PathVariable Integer id){
//        Employee employee = employeeService.getEmployeeById(id);
//        return Result.success(employee);
//    }



//    /**
//     * 修改员工信息（管理员能修改所有，员工只能修改自己）
//     * @param employeeDTO
//     * @return
//     */
//    @PutMapping("/update")
//    public Result update(@RequestBody EmployeeDTO employeeDTO){
//        log.info("修改员工的formDTO:{}", employeeDTO);
//        employeeService.update(employeeDTO);
//        return Result.success();
//    }


//
//    /**
//     * 管理员根据id删除员工
//     * @param id
//     * @return
//     */
//    @DeleteMapping("/delete/{id}")
//    public Result delete(@PathVariable Integer id){
//        log.info("根据id删除员工,{}", id);
//        employeeService.delete(id);
//        return Result.success();
//    }
}
